package com.alibaba.cloud.clinic.service.impl;

import com.alibaba.cloud.clinic.api.feign.MedicineServiceFeign;
import com.alibaba.cloud.clinic.api.feign.TechServiceFeign;
import com.alibaba.cloud.clinic.api.vm.MedSheetVM;
import com.alibaba.cloud.clinic.constant.ClinicConstant;
import com.alibaba.cloud.clinic.constant.ClinicEnum;
import com.alibaba.cloud.clinic.dao.CliOrderDetailsMapper;
import com.alibaba.cloud.clinic.dao.ClinicOrderMapper;
import com.alibaba.cloud.clinic.dao.NativeTransactionMessageMapper;
import com.alibaba.cloud.clinic.dto.ClinicOrderDTO;
import com.alibaba.cloud.clinic.dto.TransmitDataDTO;
import com.alibaba.cloud.clinic.entity.CliOrderDetails;
import com.alibaba.cloud.clinic.entity.ClinicOrder;
import com.alibaba.cloud.clinic.entity.NativeCorrelationData;
import com.alibaba.cloud.clinic.entity.NativeTransactionMessage;
import com.alibaba.cloud.clinic.service.ClinicOrderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.framework.domain.ResponseWrapper;
import com.alibaba.framework.exception.BusinessException;
import com.alibaba.framework.utils.UUIDUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ClinicOrderServiceImpl implements ClinicOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClinicOrderServiceImpl.class);

    @Autowired
    private ClinicOrderMapper clinicOrderMapper;

    @Autowired
    private CliOrderDetailsMapper cliOrderDetailsMapper;

    @Autowired
    private MedicineServiceFeign medicineServiceFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private TechServiceFeign techServiceFeign;

    @Autowired
    private NativeTransactionMessageMapper nativeTransactionMessageMapper;

    @Override
    public List<ClinicOrder> getAll() {

        Wrapper<ClinicOrder> wrapper = new QueryWrapper<>();
        List<ClinicOrder> clinicOrderList = clinicOrderMapper.selectList(wrapper);
        return clinicOrderList;
    }

    /**
     * @descript 保存处方
     * @author focus
     * @date 2025/10/14
     */
    @Transactional(rollbackFor = Exception.class)
//    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void saveOrder(List<ClinicOrderDTO> clinicOrderDTOList) {

        for (ClinicOrderDTO clinicOrderDTO : clinicOrderDTOList) {
            Date currentDate = new Date();
            // 保存处方主表
            clinicOrderDTO.setOrderId(UUIDUtil.uuid());
            ClinicOrder clinicOrder = new ClinicOrder();
            BeanUtils.copyProperties(clinicOrderDTO, clinicOrder);
            clinicOrder.setCreateTime(currentDate);
            clinicOrderMapper.insert(clinicOrder);

            // 保存处方明细表
            CliOrderDetails orderDetails = new CliOrderDetails();
            BeanUtils.copyProperties(clinicOrderDTO, orderDetails);
            orderDetails.setCreateTime(currentDate);
            cliOrderDetailsMapper.insert(orderDetails);

            if (ClinicEnum.ORDER_TYPE.MEDCINE.getValue().equals(clinicOrderDTO.getOrderType())) {
                // 开药品处方，生成发药申请，扣减药房库存
                MedSheetVM medSheetVM = new MedSheetVM();
                BeanUtils.copyProperties(clinicOrderDTO, medSheetVM);
                ResponseWrapper<Integer> responseWrapper = medicineServiceFeign.addMedSheet(medSheetVM);
                if (responseWrapper == null) {
                    throw new BusinessException("保存药品申请表失败, 请稍后再试!");
                }

                ResponseWrapper<Integer> medResponse = medicineServiceFeign.deduct(clinicOrderDTO.getOrderCode(), clinicOrderDTO.getQty());
                if (medResponse == null) {
                    throw new BusinessException("药品扣减库存失败, 请稍后再试!");
                }
            }

            // 医技类，检验检查申请
            /*if (ClinicEnum.ORDER_TYPE.EXAMINE.getValue().equals(clinicOrderDTO.getOrderType())) {

                TechSheetVM techSheetVM = new TechSheetVM();
                BeanUtils.copyProperties(clinicOrderDTO, techSheetVM);
                techServiceFeign.addMedSheet(techSheetVM);
            }*/

            String clinicOrderDTOJSON = JSON.toJSONString(clinicOrderDTO);
            // rabbitmq 检查检验的消息发送到医技服务,医技提供相关服务
            if (ClinicEnum.ORDER_TYPE.EXAMINE.getValue().equals(clinicOrderDTO.getOrderType())) {
                // 记录本地消息表
                NativeTransactionMessage nativeMessage = new NativeTransactionMessage();
                nativeMessage.setId(clinicOrderDTO.getOrderId());
                nativeMessage.setMessContent(clinicOrderDTOJSON);
                nativeMessage.setTargetServer(ClinicConstant.ALICLOUD_TECH);
                nativeMessage.setMessType(ClinicEnum.MESSAGE_TYPE.NATIVE_MESS.getValue());
                nativeMessage.setExchange(ClinicConstant.TECH_EXCHANGE);
                nativeMessage.setRoutingKey(ClinicConstant.TECH_ROUTING_KEY);
                nativeMessage.setStatus(ClinicEnum.MESSAGE_STATUS.UNSEND.getValue());
                nativeMessage.setCreateTime(currentDate);
                nativeTransactionMessageMapper.insert(nativeMessage);
            }

            // 手术类，门诊手术申请
            // 医嘱类，耗材，护理

            // 收费，写入费用


            // 处方数据上传
            if (ClinicEnum.MEDICINE_TYPE.CHINESE_HERBAL_MEDICINE.getValue().equals(clinicOrderDTO.getMedType())) {

                TransmitDataDTO transmitDataDTO = new TransmitDataDTO();
                transmitDataDTO.setTransName(ClinicConstant.INFECTIOUS_DISEASE_REPORTING);
                transmitDataDTO.setTransServer(ClinicConstant.ALICLOUD_CLINIC);
                transmitDataDTO.setTransStatus(ClinicEnum.MESSAGE_STATUS.UNSEND.getValue());
                transmitDataDTO.setUrl("localhost:10001/api/v1/transmit/data");
                transmitDataDTO.setDataContent(clinicOrderDTOJSON);
                transmitDataDTO.setUsername(clinicOrderDTO.getDoctorName());
                transmitDataDTO.setUserId(clinicOrderDTO.getDoctorId());


                String transmitDataDTOJSON = JSON.toJSONString(transmitDataDTO);
                NativeCorrelationData correlationData = new NativeCorrelationData();
                correlationData.setId(clinicOrderDTO.getOrderId());
                correlationData.setMessType(ClinicEnum.MESSAGE_TYPE.TRANSMIT_DATA.getValue());
                correlationData.setExchange(ClinicConstant.TRANS_EXCHANGE);
                correlationData.setRoutingKey(ClinicConstant.TRANS_ROUTING_KEY);
                correlationData.setMaxRetry(0);
                correlationData.setMessContent(transmitDataDTOJSON);

                rabbitTemplate.convertSendAndReceive(ClinicConstant.TRANS_EXCHANGE, ClinicConstant.TRANS_ROUTING_KEY, transmitDataDTOJSON, correlationData);

            }
        }
    }
}
